package com.example.litemall.admin.api.controller;

import com.example.litemall.admin.api.commons.ResponseUtil;
import com.example.litemall.admin.api.domain.LitemallCategory;
import com.example.litemall.admin.api.service.LitemallCategoryService;
import com.example.litemall.admin.api.vo.CategoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/admin/category")
public class AdminCategoryController {
    @Autowired
    private LitemallCategoryService categoryService;
    @GetMapping("/list")
    public Object getCategoryList(){
        List<LitemallCategory> categoryList = categoryService.getCategoryByPid(0);
        List<CategoryVo> categoryVoList = new ArrayList<>();
        for (LitemallCategory litemallCategory : categoryList) {
            CategoryVo categoryVo = new CategoryVo();
            BeanUtils.copyProperties(litemallCategory,categoryVo);
            List<CategoryVo> children = new ArrayList<>();
            List<LitemallCategory> subCategories = categoryService.getCategoryByPid(litemallCategory.getId());
            for (LitemallCategory subCategory : subCategories) {
                CategoryVo subCategoryVo = new CategoryVo();
                BeanUtils.copyProperties(subCategory,subCategoryVo);
                children.add(subCategoryVo);
            }
            categoryVo.setChildren(children);
            categoryVoList.add(categoryVo);
        }
        return ResponseUtil.okList(categoryVoList);
    }

}
